<template>
	<!--miniprogram/pagesA/room/room.wxml-->
	<!-- 在模版上放置标签 -->
	<view class="page-room">
		<!-- <view v-if="dataobj.endtime" class="endtime font15 font-323232">订单将于{{dataobj.endtime}}结束问诊</view> -->
		<!-- <view class="endtime font15 font-323232">等待患者进入</view> -->
		<trtc-room ref="trtc-component" :config="rtcConfig"></trtc-room>
		<view class="tip-toast" v-if="showTipToast">
			<view>当前房间为1v1双人通话房间</view>
			<view>不希望其他人打扰</view>
		</view>
	</view>
</template>

<script>
	import {
		genTestUserSig,
		setData
	} from "../../debug/GenerateTestUserSig";
	import trtcRoom from "../../components/trtc-room/trtc-room";

	export default {
		data() {
			return {
				dataobj: {}, //数据返回
				trtcroomshow: false, //判断
				type: '', //类型
				id: null,
				newtimer: null, //倒计时
				template: '1v1',
				rtcConfig: {
					sdkAppID: '1600002780',
					// 必要参数 开通实时音视频服务创建应用后分配的 sdkAppID
					userID: '',
					// 必要参数 用户 ID 可以由您的帐号系统指定
					userSig: '',
					// 必要参数 身份签名，相当于登录密码的作用
					template: '1v1' // 必要参数 组件模版，支持的值 1v1 grid custom ，注意：不支持动态修改, iOS 不支持 pusher 动态渲染

				},
				showTipToast: false
			};
		},

		components: {
			trtcRoom
		},
		props: {},

		/**
		 * 生命周期函数--监听页面加载
		 * @param {*} options 配置项
		 */
		onLoad: function(options) {
			this.type = options.type
			this.id = options.id
			this.Ondetails()
		},
		/**
		 * 生命周期函数--监听页面初次渲染完成
		 */
		onReady: function() {},
		onHide(e) {
			// let that = this
			// clearInterval(that.newtimer)
			// this.newtimer = null
		},
		onUnload(){
			// let that = this
			// clearInterval(that.newtimer)
			// this.newtimer = null
		},
		methods: {
			setData,
			Ondetails() {
				let that = this
				//详情
				let getRoomCode = new Promise((resolved, rejected) => {
					that.$Http({
						url: 'getRoomCode',
						data: {
							type: that.type == 'doc' ? 2 : 1,
							order_id: that.id
						},
						type: 'POST',
						token: false
					}).then(res => {
						if (res.code == 1) {
							this.dataobj = res.data
						}
						resolved(true)
					});
				})
				//时长
				let Consult = new Promise((resolved, rejected) => {
					resolved(true)
					// that.$Http({
					// 	url: 'consultationConsult',
					// 	data: {
					// 		type: that.type == 'doc' ? 2 : 1,
					// 		order_id: that.id
					// 	},
					// 	token: false
					// }).then(res => {
					// 	if (res.code == 1) {
					// 		this.dataobj.minutes = res.data.consultation_video_minutes
					// 	}
					// 	resolved(true)
					// });
				})
				Promise.all([getRoomCode, Consult, ]).then((result) => {
					// that.Onvideo()
					that.Onstart()
				}).catch((error) => {})
			},
			//医生获取结束时间
			// Onend() {
			// 	this.$Http({
			// 		url: 'getRoomCode',
			// 		data: {
			// 			type: this.type == 'doc' ? 2 : 1,
			// 			order_id: this.id
			// 		},
			// 		type: 'POST',
			// 		token: false
			// 	}).then(res => {
			// 		if (res.code == 1) {
			// 			this.dataobj.video_begin_time = res.data.video_begin_time
			// 			//倒计时
			// 			this.Ondown()
			// 		}
			// 	});
			// },
			//视频判断
			// Onvideo() {
			// 	//如果是医生进来
			// 	if (this.type == 'doc') {
			// 		//如果有开始时间
			// 		if (this.dataobj.video_begin_time) {
			// 			this.Ontime()
			// 		} else {
			// 			this.Onstart()
			// 		}
			// 	} else {
			// 		this.Ontime()
			// 	}
			// 	console.log(this.dataobj, '查看')
			// },
			//判断时间
			// Ontime() {
			// 	let that = this
			// 	// let end = (this.dataobj.video_begin_time * 1000) + (60000 * this.dataobj.minutes)
			// 	let end = (this.dataobj.video_begin_time * 1000) + (60000 * 1)
			// 	let newtime = Math.round(new Date().getTime())
			// 	var date = new Date(end);
			// 	var Y = date.getFullYear() + '-';
			// 	var M = (date.getMonth() + 1 < 10 ? '0' + (date.getMonth() + 1) : date.getMonth() + 1) + '-';
			// 	var D = date.getDate() + ' ';
			// 	var h = date.getHours() + ':';
			// 	var m = date.getMinutes() + ':';
			// 	var s = date.getSeconds();
			// 	this.dataobj.endtime = Y + M + D + h + m + s
			// 	this.dataobj.end_num = end
			// 	if (newtime <= end) {
			// 		that.Onstart()
			// 		// uni.showModal({
			// 		// 	title: '温馨提示',
			// 		// 	confirmText: '确定',
			// 		// 	confirmColor: '#b8875c',
			// 		// 	showCancel: false,
			// 		// 	content: '订单将于' + this.dataobj.endtime + '结束问诊',
			// 		// 	success: function() {
			// 		// 		that.Onstart()
			// 		// 	}
			// 		// });
			// 		that.Ondown()
			// 	} else {
			// 		this.trtcroomshow = false
			// 		uni.showModal({
			// 			title: '温馨提示',
			// 			confirmText: '确定',
			// 			confirmColor: '#b8875c',
			// 			showCancel: false,
			// 			content: '订单已于' + this.dataobj.endtime + '结束问诊',
			// 			success: function() {
			// 				uni.navigateBack({
			// 					delta: 1
			// 				})
			// 			}
			// 		});
			// 	}

			// },
			//开始视频
			Onstart() {
				let that = this
				that.trtcroomshow = true
				wx.setKeepScreenOn({
					keepScreenOn: true
				}); // 获取 rtcroom 实例
				that.trtcComponent = that.$refs['trtc-component']; // 监听TRTC Room 关键事件
				//判断时间
				// that.Ontime()
				that.bindTRTCRoomEvent(); // 将String 类型的 true false 转换成 boolean
				that.rtcConfig.userID = that.dataobj.openid
				that.enterRoom({
					userID: that.dataobj.openid,
				})
			},
			//倒计时
			// Ondown() {
			// 	let that = this
			// 	that.newtimer = setInterval(function() {
			// 		let newtime = Math.round(new Date().getTime())
			// 		if (newtime <= that.dataobj.end_num) {
			// 			that.timeshow = true
			// 		} else {
			// 			that.timeshow = false
			// 			clearInterval(that.newtimer)
			// 			uni.navigateBack({
			// 				delta: 1
			// 			})
			// 			// uni.showModal({
			// 			// 	title: '提示',
			// 			// 	confirmText: '确定',
			// 			// 	confirmColor: '#b8875c',
			// 			// 	showCancel: false,
			// 			// 	content: '视频问诊已结束',
			// 			// 	success: function() {
			// 			// 		uni.navigateBack({
			// 			// 			delta: 1
			// 			// 		})
			// 			// 	}
			// 			// });
			// 		}
			// 	}, 1000)
			// },
			enterRoom: function(params) {
				params.userID = params.userID;
				params.roomID = this.dataobj.room_code;
				const Signature = genTestUserSig(params.userID);
				params.sdkAppID = Signature.sdkAppID;
				params.userSig = Signature.userSig;
				this.rtcConfig.userSig = params.userSig
				this.rtcConfig.enableCamera = true
				this.setData({
					rtcConfig: this.rtcConfig
				}, () => {
					this.trtcComponent.enterRoom({
						roomID: params.roomID * 1
					}).then(() => {

					}).catch(res => {
						console.error('* room joinRoom 进房失败:', res);
					});
				});
			},
			bindTRTCRoomEvent: function() {
				const TRTC_EVENT = this.trtcComponent.EVENT;
				this.timestamp = []; // 初始化事件订阅

				this.trtcComponent.on(TRTC_EVENT.LOCAL_JOIN, event => {
					this.trtcComponent.publishLocalVideo();
					this.trtcComponent.publishLocalAudio();
				});
				this.trtcComponent.on(TRTC_EVENT.LOCAL_LEAVE, event => {
					console.log('* room LOCAL_LEAVE', event);
				});
				this.trtcComponent.on(TRTC_EVENT.ERROR, event => {
					console.log('* room ERROR', event);
				}); // 远端用户进房

				this.trtcComponent.on(TRTC_EVENT.REMOTE_USER_JOIN, event => {
					// if (this.dataobj.video_begin_time == null) {
					// 	//获取结束时间
					// 	this.Onend()
					// }
					this.timestamp.push(new Date()); // 1v1视频通话时限制人数为两人的简易逻辑，建议通过后端实现房间人数管理
					// 2人以上同时进行通话请选择网格布局
					if (this.template === '1v1' && this.timestamp.length > 1) {
						const interval = this.timestamp[1] - this.timestamp[0];

						if (interval < 1000) {
							// 房间里已经有两个人
							this.setData({
								showTipToast: true
							}, () => {
								setTimeout(() => {
									this.setData({
										showTipToast: false
									});
									wx.navigateBack({
										delta: 1
									});
								}, 4000);
							});
						}
					}
				}); // 远端用户退出

				this.trtcComponent.on(TRTC_EVENT.REMOTE_USER_LEAVE, event => {
					console.log('* room REMOTE_USER_LEAVE', event, this.trtcComponent.getRemoteUserList());

					if (this.template === '1v1') {
						this.timestamp = [];
					}

					if (this.template === '1v1' && this.remoteUser === event.data.userID) {
						this.remoteUser = null;
					}
				}); // 远端用户推送视频

				this.trtcComponent.on(TRTC_EVENT.REMOTE_VIDEO_ADD, event => {
					console.log('* room REMOTE_VIDEO_ADD', event, this.trtcComponent
						.getRemoteUserList()); // 订阅视频

					const userList = this.trtcComponent.getRemoteUserList();
					const data = event.data;

					if (this.template === '1v1' && (!this.remoteUser || this.remoteUser === data.userID)) {
						// 1v1 只订阅第一个远端流
						this.remoteUser = data.userID;
						this.trtcComponent.subscribeRemoteVideo({
							userID: data.userID,
							streamType: data.streamType
						});
					} else if (this.template === 'grid') {
						this.trtcComponent.subscribeRemoteVideo({
							userID: data.userID,
							streamType: data.streamType
						});
					}

					if (this.template === 'custom' && data.userID && data.streamType) {
						let index = userList.findIndex(item => {
							return item.userID === data.userID;
						});
						index++;
						const y = 320 * index + 160; // 设置远端视图坐标和尺寸

						this.trtcComponent.setViewRect({
							userID: data.userID,
							streamType: data.streamType,
							xAxis: '480rpx',
							yAxis: y + 'rpx',
							width: '240rpx',
							height: '320rpx'
						});
					}
				}); // 远端用户取消推送视频

				this.trtcComponent.on(TRTC_EVENT.REMOTE_VIDEO_REMOVE, event => {
					console.log('* room REMOTE_VIDEO_REMOVE', event, this.trtcComponent.getRemoteUserList());
				}); // 远端用户推送音频

				this.trtcComponent.on(TRTC_EVENT.REMOTE_AUDIO_ADD, event => {
					console.log('* room REMOTE_AUDIO_ADD', event, this.trtcComponent
						.getRemoteUserList()); // 订阅音频

					const data = event.data;

					if (this.template === '1v1' && (!this.remoteUser || this.remoteUser === data.userID)) {
						this.remoteUser = data.userID;
						this.trtcComponent.subscribeRemoteAudio({
							userID: data.userID
						});
					} else if (this.template === 'grid' || this.template === 'custom') {
						this.trtcComponent.subscribeRemoteAudio({
							userID: data.userID
						});
					} // 如果不订阅就不会自动播放音频
					// this.trtcComponent.subscribeRemoteAudio({ userID: data.userID })

				}); // 远端用户取消推送音频

				this.trtcComponent.on(TRTC_EVENT.REMOTE_AUDIO_REMOVE, event => {
					console.log('* room REMOTE_AUDIO_REMOVE', event, this.trtcComponent.getRemoteUserList());
				});
			}
		}
	};
</script>
<style>
	.page-room {
		width: 100vw;
		height: 100vh;
		overflow: hidden;
	}

	.endtime {
		position: fixed;
		top: 50rpx;
		width: 750rpx;
		text-align: center;
		z-index: 9999;
	}

	.tip-toast {
		position: absolute;
		top: 40vh;
		width: 70vw;
		left: 15vw;
		border-radius: 12rpx;
		height: 20vh;
		background: rgba(0, 0, 0, 0.8);
		color: white;
		display: flex;
		flex-direction: column;
		align-items: center;
		justify-content: center;

	}

	.tip-toast view {
		padding: 20rpx 0;
		font-size: 32rpx;
	}
</style>
